package com.example.config;

import co.elastic.clients.elasticsearch.ElasticsearchClient;
import co.elastic.clients.elasticsearch._types.mapping.Property;
import co.elastic.clients.elasticsearch.indices.CreateIndexResponse;
import co.elastic.clients.elasticsearch.indices.ExistsRequest;
import co.elastic.clients.transport.endpoints.BooleanResponse;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.boot.context.event.ApplicationReadyEvent;
import org.springframework.context.event.EventListener;
import org.springframework.stereotype.Component;

import java.io.IOException;
import java.util.Collections;
import java.util.HashMap;
import java.util.Map;

/**
 * Elasticsearch索引初始化器
 * 在应用启动时创建必要的索引和映射
 */
@Slf4j
@Component
@RequiredArgsConstructor
public class ElasticsearchIndexInitializer {

    private static final String INDEX_NAME = "risk_indicators";
    
    private final ElasticsearchClient esClient;

    /**
     * 应用启动后初始化索引
     */
    @EventListener(ApplicationReadyEvent.class)
    public void initializeIndices() {
        try {
            createRiskIndicatorIndex();
        } catch (IOException e) {
            log.error("Failed to initialize Elasticsearch indices: {}", e.getMessage(), e);
        }
    }

    /**
     * 创建风控指标索引
     */
    private void createRiskIndicatorIndex() throws IOException {
        // 检查索引是否已存在
        BooleanResponse existsResponse = esClient.indices().exists(
                ExistsRequest.of(e -> e.index(INDEX_NAME))
        );

        if (existsResponse.value()) {
            log.info("Index '{}' already exists", INDEX_NAME);
            return;
        }

        // 定义字段映射
        Map<String, Property> properties = new HashMap<>();
        
        // ID字段
        properties.put("id", Property.of(p -> p.keyword(k -> k)));
        
        // 用户ID字段
        properties.put("userId", Property.of(p -> p.keyword(k -> k)));
        
        // 指标类型字段
        properties.put("type", Property.of(p -> p.keyword(k -> k)));
        
        // 指标名称字段 - 支持全文搜索和关键字搜索
        properties.put("name", Property.of(p -> p
                .text(t -> t)
                .fields(Map.of("keyword", Property.of(f -> f.keyword(k -> k))))
        ));


        // 指标值字段 - 数值类型
        properties.put("value", Property.of(p -> p.double_(d -> d)));
        
        // 风险等级字段 - 枚举类型
        properties.put("riskLevel", Property.of(p -> p.keyword(k -> k)));
        
        // 计算时间字段 - 日期类型
        properties.put("calculatedAt", Property.of(p -> p.date(d -> d)));
        
        // 有效期字段 - 日期类型
        properties.put("validUntil", Property.of(p -> p.date(d -> d)));
        
        // 来源字段
        properties.put("source", Property.of(p -> p.keyword(k -> k)));
        
        // 描述字段 - 文本类型
        properties.put("description", Property.of(p -> p
                .text(t -> t)
                .fields(Map.of("keyword", Property.of(f -> f.keyword(k -> k))))
        ));
        
        // 属性字段 - 对象类型
        properties.put("attributes", Property.of(p -> p.object(o -> o)));

        // 创建索引
        CreateIndexResponse createResponse = esClient.indices().create(c -> c
                .index(INDEX_NAME)
                .mappings(m -> m.properties(properties))
                .settings(s -> s
                        .numberOfShards("1")
                        .numberOfReplicas("1")
                )
        );

        log.info("Created index '{}': {}", INDEX_NAME, createResponse.acknowledged());
    }
}